package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.RecrPageStorage;
import com.cdgeekcamp.redas.db.model.RecrPageStorageRepository;
import com.cdgeekcamp.redas.lib.core.api.receivedParameter.RecrPage;
import com.cdgeekcamp.redas.lib.core.jsonObject.JsonObject;
import com.cdgeekcamp.redas.lib.core.util.RedasString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

@Component
public class RecrPageStorageBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private RecrPageStorageRepository recrPageStorages;

    public Integer build(RecrPage recrPage, Integer... relatedIds) throws NoSuchAlgorithmException {
        String uuid = recrPage.getSpiderUuid();

        JsonObject recrPageJson = new JsonObject();
        String content = recrPageJson.toJson(recrPage);

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(content.getBytes(StandardCharsets.UTF_8));
        String hash_str = RedasString.bytesToHex(hash);

        Optional<RecrPageStorage> recrPageStorageOpt = recrPageStorages.findByHash(hash_str);
        RecrPageStorage recrPageStorage;

        if (recrPageStorageOpt.isEmpty()) {
            recrPageStorage = recrPageStorages.save(new RecrPageStorage(content, uuid, hash_str));
            log.info(String.format("元数据：%s 不存在，新建中......", hash_str));
        } else {
            recrPageStorage = recrPageStorageOpt.get();
            log.info(String.format("元数据：%s 已经存在", hash_str));
        }

        return recrPageStorage.getId();
    }
}
